/*
@Author   : Uyynot
@Email    : uyynot@qq.com
@Time     : 2023/8/16 14:30
@File     : mysql.go
@Project  : web_scaff
@Desc     :
*/
package configs

import (
	"fmt"
	"web_scaff/models"

	"go.uber.org/zap"

	"gorm.io/driver/mysql"

	"gorm.io/gorm"
)

type Mysql struct {
	Host         string `json:"host" mapstructure:"host"`
	Port         uint   `json:"port" mapstructure:"port"`
	Config       string `json:"config" mapstructure:"config"`
	DbName       string `json:"db_name" mapstructure:"db_name"`
	User         string `json:"user" mapstructure:"user"`
	Pwd          string `json:"pwd" mapstructure:"pwd"`
	MaxIdleConns int    `json:"max_idle_conns" mapstructure:"max_idle_conns"`
	MaxOpenConns int    `json:"max_open_conns" mapstructure:"max_open_conns"`
}

var Db *gorm.DB

func init() {
	dsn := fmt.Sprintf("%s:%s@(%s)/%s?%s", Conf.Mysql.User, Conf.Mysql.Pwd, Conf.Mysql.Host, Conf.Mysql.DbName, Conf.Mysql.Config)
	var err error
	Db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		zap.L().Error("数据库连接失败：", zap.Error(err))
		panic(fmt.Errorf("连接数据库失败：%s", err))
	}
	mysqlDB, err := Db.DB()
	if err != nil {
		zap.L().Error("数据库出错：", zap.Error(err))
		panic(fmt.Errorf("数据库出错：%s", err))
	}
	mysqlDB.SetMaxIdleConns(Conf.Mysql.MaxIdleConns)
	mysqlDB.SetMaxOpenConns(Conf.Mysql.MaxOpenConns)

	Db.AutoMigrate(&models.User{})
}
